﻿using System.Drawing;
using System.Drawing.Drawing2D;

namespace DeviceFaultPushService.SystemService
{
    public class VerificationServices
    {
        public static void Start(out Bitmap captchaImage, out string validationKey)
        {
            GenerateCaptchaImage(GenerateRandomCaptchaText(), out captchaImage, out validationKey);
        }

        private static void GenerateCaptchaImage(string captchaText, out Bitmap captchaImage, out string validationKey)
        {
            // 设置验证码图片的尺寸  
            int width = 200;
            int height = 60;

            // 创建验证码图片  
            captchaImage = new Bitmap(width, height);

            // 创建绘图对象  
            using (Graphics g = Graphics.FromImage(captchaImage))
            {
                // 设置绘图质量  
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.Clear(Color.White);

                // 设置字体和颜色  
                System.Drawing.Font font = new System.Drawing.Font("Arial", 20, FontStyle.Bold);
                Brush textBrush = new SolidBrush(Color.FromArgb(30, 50, 100));

                // 绘制验证码文本  
                Random random = new Random();
                float x = random.Next(0, width - 110);
                float y = random.Next(0, height - 25);
                g.DrawString(captchaText, font, textBrush, x, y);

                // 添加噪点  
                for (int i = 0; i < 100; i++)
                {
                    int xPos = random.Next(width);
                    int yPos = random.Next(height);
                    g.FillEllipse(Brushes.Black, xPos, yPos, 1, 1);
                }

                // 添加干扰线  
                for (int i = 0; i < 5; i++)
                {
                    int x1 = random.Next(width);
                    int y1 = random.Next(height);
                    int x2 = random.Next(width);
                    int y2 = random.Next(height);
                    g.DrawLine(Pens.Gray, x1, y1, x2, y2);
                }
            }
            // 生成验证码的验证键  
            validationKey = captchaText;
        }

        private static string GenerateRandomCaptchaText()
        {
            // 创建一个Random实例  
            Random random = new Random();

            // 生成一个随机的6位数字  
            int randomSixDigitNumber = random.Next(100000, 1000000); // 包含100000和999999 

            return randomSixDigitNumber.ToString();
        }
    }
}
